//
//  shell_processor.cpp
//  CoMmand
//
//  Created by Zhiqiang Bao on 15-1-16.
//  Copyright (c) 2015年 Zhiqiang Bao. All rights reserved.
//

#include "shell_processor.h"
#include <iostream>
#include <unistd.h>

/**
 *  运行shell命令，并输出到对应的buf
 *
 *  @param cmdstring shell命令
 *  @param buf       储存输出的buffer
 *  @param len       buffer的最大长度
 *
 *  @return -1失败 0正确
 */
int system2buf(char* cmdstring, char* buf, int len)

{
    int   fd[2];
    pid_t pid;
    ssize_t   n, count;
    memset(buf, 0, len);
    if (pipe(fd) < 0)
    {
        return -6;
    }
    if ((pid = fork()) < 0)
    {
        return -5;
    }
    else if (pid > 0)     /* parent process */
    {
        close(fd[1]);     /* close write end */
        count = 0;
        while (count < len &&  (n = read(fd[0], buf + count, len - count)) > 0) {
            count += n;
        }
        close(fd[0]);
        
        int ret = waitpid(-1, NULL, 0);
        if (ret < 0)
        {
            return -4;
        }
    }
    else                  /* child process */
    {
        close(fd[0]);     /* close read end */
        if (fd[1] != STDERR_FILENO)
        {
            // redirect the fd
            if (dup2(fd[1], STDERR_FILENO) != STDERR_FILENO)
            {
                return -1;
            }
        }
        
        if (fd[1] != STDOUT_FILENO) {
            
            // redirect the fd
            if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
            {
                return -2;
            }
        }
        close(fd[1]);
        
        if (execl("/bin/sh", "sh", "-c", cmdstring, NULL) == -1)
        {
            return -3;
        }
    }
    return 0;
}

